<?php
// +----------------------------------------------------------------------
// | CoreThink [ Simple Efficient Excellent ]
// +----------------------------------------------------------------------
// | Copyright (c) 2014 http://www.corethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: jry <598821125@qq.com> <http://www.corethink.cn>
// +----------------------------------------------------------------------

require_once(APP_PATH . '/Common/Common/developer.php'); //加载开发者二次开发公共函数库

function get_descriptions_to_option($tablename, $fieldname){
	$data=M('descriptions')->where(array('tablename'=>$tablename,'fieldname'=>$fieldname,'status'=>array('gt',0)))->select();
	$arr=array();
	foreach($data as $val){
		$arr[$val['fieldvalue']]=$val['title'];
	}
	return $arr; //短信功能待开发
}
/**
 * 二级密码验证
 */
function check_psdtwo($psdtwo,$uid){
	$member=M('User');
	$userinfo=$member->where(array('id'=>$uid))->find();
	$psdtwo = user_md5($psdtwo);
	if($psdtwo!=$userinfo['two_password']){
		return false;
	}else{
		return true;
	}
}
function WSTIsMobile() {
	$_SERVER['ALL_HTTP'] = isset($_SERVER['ALL_HTTP']) ? $_SERVER['ALL_HTTP'] : '';
	$mobile_browser = '0';
	if(preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|iphone|ipad|ipod|android|xoom)/i', strtolower($_SERVER['HTTP_USER_AGENT'])))
		$mobile_browser++;
	if((isset($_SERVER['HTTP_ACCEPT'])) and (strpos(strtolower($_SERVER['HTTP_ACCEPT']),'application/vnd.wap.xhtml+xml') !== false))
		$mobile_browser++;
	if(isset($_SERVER['HTTP_X_WAP_PROFILE']))
		$mobile_browser++;
	if(isset($_SERVER['HTTP_PROFILE']))
		$mobile_browser++;
	$mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'],0,4));
	$mobile_agents = array(
			'w3c ','acs-','alav','alca','amoi','audi','avan','benq','bird','blac',
			'blaz','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno',
			'ipaq','java','jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-',
			'maui','maxo','midp','mits','mmef','mobi','mot-','moto','mwbp','nec-',
			'newt','noki','oper','palm','pana','pant','phil','play','port','prox',
			'qwap','sage','sams','sany','sch-','sec-','send','seri','sgh-','shar',
			'sie-','siem','smal','smar','sony','sph-','symb','t-mo','teli','tim-',
			'tosh','tsm-','upg1','upsi','vk-v','voda','wap-','wapa','wapi','wapp',
			'wapr','webc','winw','winw','xda','xda-'
	);
	if(in_array($mobile_ua, $mobile_agents))$mobile_browser++;
	if(strpos(strtolower($_SERVER['ALL_HTTP']), 'operamini') !== false)$mobile_browser++;
	if(strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows') !== false)$mobile_browser=0;
	if(strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows phone') !== false)$mobile_browser++;
	if($mobile_browser>0){
		return true;
	}else{
		return false;
	}
}
/**
 * 获取网站域名
 */
function WSTDomain(){
    $server = $_SERVER['HTTP_HOST'];
    $http = is_ssl()?'https://':'http://';
    return $http.$server.__ROOT__;
}
/**
 * 获取系统根目录
 */
function WSTRootPath(){
    return dirname(dirname(dirname(dirname(__File__))));
}
/**
 * 获取网站根域名
 */
function WSTRootDomain(){
    $server = $_SERVER['HTTP_HOST'];
    $http = is_ssl()?'https://':'http://';
    return $http.$server;
}
/**
 * 获取用户数据
 * @param unknown $k
 * @return Ambigous <>
 */
function get_user_data($k,$v){
    $info=M('User')->where(array('id'=>$k))->find();
    return $info[$v];
}

/**
 *  获取当前登陆账号指定币种的金额
 * @param int $currency_id 币种ID
 * @param char $field  num  forzen_num
 * @return array 当前登陆人账号信息
 */
function getUserMoney($currency_id,$field,$uinfo=NULL){
    if (empty($currency_id)){
        switch ($field){
            case 'num':$field='money';break;
            case 'forzen_num':$field='forzen_money';break;
            default:$field='money';
        }
        $uinfo[$field];
    }else {
        $currency_user= M('Currency_user')->where("member_id={$uinfo['id']} and currency_id=$currency_id")->find();
    }
    return  isset($uinfo[$field])? $uinfo[$field]:$currency_user[$field];
}

/**
 * 获取用户状态
 * @param unknown $k
 * @return Ambigous <>
 */
function get_user_status($k){
    $info=M('User')->where(array('id'=>$k))->find();
    return $info['status'];
}

/**
 * 获取用户编号
 * @param unknown $k
 * @return Ambigous <>
 */
function get_username($k=''){
    $info=M('User')->where(array('id'=>$k))->find();
    if(empty($info)){
        return "无";
    }else{
        return $info['username'];
    }

}

/**
 * 日志信息
 */
function add_log_message($log_data='',$message_data=''){
    if(!empty($log_data)){
        $log=D("Common/Log");
        $log->addlog($log_data);
    }
    if(!empty($message_data)){
        $user_message=D("Common/UserMessage");
        $user_message->addmessage($message_data);
    }
}

/**
 * 根据配置类型解析配置
 * @param  string $type  配置类型
 * @param  string  $value 配置值
 */
function parse_attr($value, $type){
    switch ($type) {
        default: //解析"1:1\r\n2:3"格式字符串为数组
            $array = preg_split('/[,;\r\n]+/', trim($value, ",;\r\n"));
            if(strpos($value,':')){
                $value  = array();
                foreach ($array as $val) {
                    list($k, $v) = explode(':', $val);
                    $value[$k]   = $v;
                }
            }else{
                $value = $array;
            }
            break;
    }
    return $value;
}

/**
 * 字符串截取(中文按2个字符数计算)，支持中文和其他编码
 * @static
 * @access public
 * @param str $str 需要转换的字符串
 * @param str $start 开始位置
 * @param str $length 截取长度
 * @param str $charset 编码格式
 * @param str $suffix 截断显示字符
 * @return str
 */
function get_str($str, $start, $length, $charset='utf-8', $suffix=true) {
    $str = trim($str);
    $length = $length * 2;
    if($length){
        //截断字符
        $wordscut = '';
        if(strtolower($charset) == 'utf-8'){
            //utf8编码
            $n = 0;
            $tn = 0;
            $noc = 0;
            while($n < strlen($str)){
                $t = ord($str[$n]);
                if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)){
                    $tn = 1;
                    $n++;
                    $noc++;
                }elseif(194 <= $t && $t <= 223){
                    $tn = 2;
                    $n += 2;
                    $noc += 2;
                }elseif(224 <= $t && $t < 239){
                    $tn = 3;
                    $n += 3;
                    $noc += 2;
                }elseif(240 <= $t && $t <= 247){
                    $tn = 4;
                    $n += 4;
                    $noc += 2;
                }elseif(248 <= $t && $t <= 251){
                    $tn = 5;
                    $n += 5;
                    $noc += 2;
                }elseif($t == 252 || $t == 253){
                    $tn = 6;
                    $n += 6;
                    $noc += 2;
                }else{
                    $n++;
                }
                if ($noc >= $length){
                    break;
                }
            }
            if($noc > $length){
                $n -= $tn;
            }
            $wordscut = substr($str, 0, $n);
        }else{
            for($i = 0; $i < $length - 1; $i++){
                if(ord($str[$i]) > 127) {
                    $wordscut .= $str[$i].$str[$i + 1];
                    $i++;
                } else {
                    $wordscut .= $str[$i];
                }
            }
        }
        if($wordscut == $str){
            return $str;
        }
        return $suffix ? trim($wordscut).'...' : trim($wordscut);
    }else{
        return $str;
    }
}

/**
 * 过滤标签，输出纯文本
 * @param string $str 文本内容
 * @return string 处理后内容
 * @author jry <598821125@qq.com>
 */
function html2text($str){
    $str = preg_replace("/<sty(.*)\\/style>|<scr(.*)\\/script>|<!--(.*)-->/isU","",$str);
    $alltext = "";
    $start = 1;
    for($i=0;$i<strlen($str);$i++){
        if($start==0 && $str[$i]==">"){
            $start = 1;
        }
        else if($start==1){
            if($str[$i]=="<"){
                $start = 0;
                $alltext .= " ";
            }
            else if(ord($str[$i])>31){
                $alltext .= $str[$i];
            }
        }
    }
    $alltext = str_replace("　"," ",$alltext);
    $alltext = preg_replace("/&([^;&]*)(;|&)/","",$alltext);
    $alltext = preg_replace("/[ ]+/s"," ",$alltext);
    return $alltext;
}

/**
 * 敏感词过滤替换
 * @param  string $text 待检测内容
 * @param  array $sensitive 待过滤替换内容
 * @param  string $suffix 替换后内容
 * @return bool
 * @author jry <598821125@qq.com>
 */
function sensitive_filter($text, $sensitive = null, $suffix = '**'){
    if(!$sensitive){
        $sensitive = C('SENSITIVE_WORDS');
    }
    $sensitive_words = explode(',', $sensitive);
    $sensitive_words_replace = array_combine($sensitive_words,array_fill(0,count($sensitive_words), $suffix));
    return strtr($text, $sensitive_words_replace);
}

/**
 * 解析文档内容
 * @param string $str 待解析内容
 * @return string
 * @author jry <598821125@qq.com>
 */
function parse_content($str){
    return preg_replace('/(<img.*?)src=/i', "$1 class='lazy img-responsive' data-original=", $str);//将img标签的src改为data-original用户前台图片lazyload加载
}

/**
 * 友好的时间显示
 * @param int    $sTime 待显示的时间
 * @param string $type  类型. normal | mohu | full | ymd | other
 * @param string $alt   已失效
 * @return string
 * @author jry <598821125@qq.com>
 */
function friendly_date($sTime, $type = 'normal', $alt = 'false'){
    if (!$sTime)
        return '';
    //sTime=源时间，cTime=当前时间，dTime=时间差
    $cTime      =   time();
    $dTime      =   $cTime - $sTime;
    $dDay       =   intval(date("z",$cTime)) - intval(date("z",$sTime));
    //$dDay     =   intval($dTime/3600/24);
    $dYear      =   intval(date("Y",$cTime)) - intval(date("Y",$sTime));
    //normal：n秒前，n分钟前，n小时前，日期
    if($type=='normal'){
        if( $dTime < 60 ){
            if($dTime < 10){
                return '刚刚';
            }else{
                return intval(floor($dTime / 10) * 10)."秒前";
            }
        }elseif( $dTime < 3600 ){
            return intval($dTime/60)."分钟前";
            //今天的数据.年份相同.日期相同.
        }elseif( $dYear==0 && $dDay == 0  ){
            //return intval($dTime/3600)."小时前";
            return '今天'.date('H:i',$sTime);
        }elseif($dYear==0){
            return date("m月d日 H:i",$sTime);
        }else{
            return date("Y-m-d H:i",$sTime);
        }
    }elseif($type=='mohu'){
        if( $dTime < 60 ){
            return $dTime."秒前";
        }elseif( $dTime < 3600 ){
            return intval($dTime/60)."分钟前";
        }elseif( $dTime >= 3600 && $dDay == 0  ){
            return intval($dTime/3600)."小时前";
        }elseif( $dDay > 0 && $dDay<=7 ){
            return intval($dDay)."天前";
        }elseif( $dDay > 7 &&  $dDay <= 30 ){
            return intval($dDay/7) . '周前';
        }elseif( $dDay > 30 ){
            return intval($dDay/30) . '个月前';
        }
        //full: Y-m-d , H:i:s
    }elseif($type=='full'){
        return date("Y-m-d , H:i:s",$sTime);
    }elseif($type=='ymd'){
        return date("Y-m-d",$sTime);
    }else{
        if( $dTime < 60 ){
            return $dTime."秒前";
        }elseif( $dTime < 3600 ){
            return intval($dTime/60)."分钟前";
        }elseif( $dTime >= 3600 && $dDay == 0  ){
            return intval($dTime/3600)."小时前";
        }elseif($dYear==0){
            return date("Y-m-d H:i:s",$sTime);
        }else{
            return date("Y-m-d H:i:s",$sTime);
        }
    }
}

/**
 * 时间戳格式化
 * @param int $time
 * @return string 完整的时间显示
 * @author jry <598821125@qq.com>
 */
function time_format($time = NULL, $format='Y-m-d H:i'){
    $time = $time === NULL ? NOW_TIME : intval($time);
    return date($format, $time);
}

/**
 * 解析数据库语句函数
 * @param string $sql  sql语句   带默认前缀的
 * @param string $tablepre  自己的前缀
 * @return multitype:string 返回最终需要的sql语句
 */
function sql_split($sql, $tablepre){
    if($tablepre != "ct_"){
        $sql = str_replace("ct_", $tablepre, $sql);
    }
    $sql = preg_replace("/TYPE=(InnoDB|MyISAM|MEMORY)( DEFAULT CHARSET=[^; ]+)?/", "ENGINE=\\1 DEFAULT CHARSET=utf8", $sql);
    if($r_tablepre != $s_tablepre){
        $sql = str_replace($s_tablepre, $r_tablepre, $sql);
    }
    $sql = str_replace("\r", "\n", $sql);
    $ret = array();
    $num = 0;
    $queriesarray = explode(";\n", trim($sql));
    unset($sql);
    foreach($queriesarray as $query){
        $ret[$num] = '';
        $queries = explode("\n", trim($query));
        $queries = array_filter($queries);
        foreach($queries as $query){
            $str1 = substr($query, 0, 1);
            if($str1 != '#' && $str1 != '-'){
                $ret[$num] .= $query;
            }
        }
        $num++;
    }
    return $ret;
}

/**
 * 执行文件中SQL语句函数
 * @param string $file sql语句文件路径
 * @param string $tablepre  自己的前缀
 * @return multitype:string 返回最终需要的sql语句
 */
function execute_sql_from_file($file){
    $sql_data = file_get_contents($file);
    $sql_format = sql_split($sql_data, C('DB_PREFIX'));
    $counts = count($sql_format);
    for($i = 0; $i < $counts; $i++){
        $sql = trim($sql_format[$i]);
        D()->execute($sql);
    }
    return true;
}


/**
 * 系统非常规MD5加密方法
 * @param  string $str 要加密的字符串
 * @return string
 * @author jry <598821125@qq.com>
 */
function user_md5($str, $auth_key){
    if(!$auth_key){
        $auth_key = C('AUTH_KEY');
    }
    return '' === $str ? '' : md5(sha1($str) . $auth_key);
}

/**
 * 检测用户是否登录
 * @return integer 0-未登录，大于0-当前登录用户ID
 * @author jry <598821125@qq.com>
 */
function is_login(){
    return D('User')->isLogin();
}

/**
 * 根据用户ID获取用户信息
 * @param  integer $id 用户ID
 * @param  string $field
 * @return array  用户信息
 * @author jry <598821125@qq.com>
 */
function get_user_info($id, $field){
    $userinfo = D('User')->find($id);
    if($field){
        $userinfo[$field];
    }
    return $userinfo;
}

/**
 * 获取上传文件路径
 * @param  int $id 文件ID
 * @return string
 * @author jry <598821125@qq.com>
 */
function get_cover($id, $type){
    $upload_info = D('PublicUpload')->find($id);
    $url = $upload_info['real_path'];
    if(!$url){
        switch($type){
            case 'default' : //默认图片
                $url = C('TMPL_PARSE_STRING.__HOME_IMG__').'/logo/default.gif';
                break;
            case 'avatar' : //用户头像
                $url = C('TMPL_PARSE_STRING.__HOME_IMG__').'/avatar/avatar'.rand(1,7).'.png';
                break;
            default: //文档列表默认图片
                break;
        }
    }
    return $url;
}

/**
 * 获取上传文件信息
 * @param  int $id 文件ID
 * @return string
 * @author jry <598821125@qq.com>
 */
function get_upload_info($id, $field){
    $upload_info = D('PublicUpload')->where('status = 1')->find($id);
    if($field){
        if(!$upload_info[$field]){
            return $upload_info['id'];
        }else{
            return $upload_info[$field];
        }
    }
    return $upload_info;
}


/**
 * 获取所有数据并转换成一维数组
 * @author jry <598821125@qq.com>
 */
function select_list_as_tree($model, $map = null, $extra = null){
    //获取列表
    $con['status'] = array('eq', 1);
    if($map){
        $con = array_merge($con, $map);
    }
    $list = D($model)->where($con)->select();

    //转换成树状列表(非严格模式)
    $tree = new \Common\Util\Tree();
    $list = $tree->toFormatTree($list, 'title', 'id', 'pid', 0, false);

    if($extra){
        $result[0] = $extra;
    }

    //转换成一维数组
    foreach($list as $val){
        $result[$val['id']] = $val['title_show'];
    }
    return $result;
}

/**
 * 系统邮件发送函数
 * @param string $receiver 收件人
 * @param string $subject 邮件主题
 * @param string $body 邮件内容
 * @param string $attachment 附件列表
 * @return boolean
 * @author jry <598821125@qq.com>
 */
function send_mail($receiver, $subject, $body, $attachment){
    return R('Addons://Email/Email/sendMail', array($receiver, $subject, $body, $attachment));
}

/**
 * 短信发送函数
 * @param string $receiver 接收短信手机号码
 * @param string $body 短信内容
 * @return boolean
 * @author jry <598821125@qq.com>
 */
function send_mobile_message($receiver, $body){
    return false; //短信功能待开发
}


/**
 * 处理插件钩子
 * @param string $hook   钩子名称
 * @param mixed $params 传入参数
 * @return void
 * @author jry <598821125@qq.com>
 */
function hook($hook, $params = array()){
    \Think\Hook::listen($hook,$params);
}

/**
 * 获取插件类的类名
 * @param strng $name 插件名
 * @author jry <598821125@qq.com>
 */
function get_addon_class($name){
    $class = "Addons\\{$name}\\{$name}Addon";
    return $class;
}

/**
 * 插件显示内容里生成访问插件的url
 * @param string $url url
 * @param array $param 参数
 * @author jry <598821125@qq.com>
 */
function addons_url($url, $param = array()){
    return D('Addon')->getAddonUrl($url, $param);
}

function is_line_text($k){
    $text=array('0'=>'未上线','1'=>'已上线');
    return $text[$k];
}
function is_lock_text($k){
    $text=array('1'=>'未开启','0'=>'已开启');
    return $text[$k];
}
/**
 * 获取充值申请状态
 * @param unknown $k
 */
function get_recharge_status_text($k){
    $recharge_status_list=M('Descriptions')->where(array('tablename'=>'recharge_status'))->select();
    $recharge_status_arr=list_to_arr($recharge_status_list,'fieldvalue','title');
    return $recharge_status_arr[$k];
}
/**
 * 获取提现状态
 * @param unknown $k
 */
function get_with_status_text($k){
    $with_status_list=M('Descriptions')->where(array('tablename'=>'withdrawals_status'))->select();
    $with_status_arr=list_to_arr($with_status_list,'fieldvalue','title');
    return $with_status_arr[$k];
}
/**
 * 获取流水类型
 * @param unknown $k
 */
function get_bonus_change_type_text($k){
    $bonus_change_type_list=M('Descriptions')->where(array('tablename'=>'detailed'))->select();
    $bonus_change_type_arr=list_to_arr($bonus_change_type_list,'fieldvalue','title');
    return $bonus_change_type_arr[$k];
}

/**
 *数据转成特点数组
 * @param unknown $list
 * @param unknown $k
 * @param unknown $v
 * @return unknown
 */
function list_to_arr($list,$k,$v){
    foreach ($list as $vo){
        $arr[$vo[$k]]=$vo[$v]?$vo[$v]:0;
    }
    return $arr;
}

/**
* 根据ID返回具体分类
* @param string $id
* @return boolean|array $list;
*/

function getCatById($id=null){
    if (empty($id)){
        return false;
    }
    return M('Article_category')->where("id=$id")->find();
}

/**
 * 返回指定父类下面的二级分类
 * @param string $parentId
 * @return boolean|array $list;
 */
function getChildCatByParentCat($parentId=null){
    if (empty($parentId)){
        return false;
    }
    return M('Article_category')->where("parent_id=$parentId")->select();
}
/**
 * 获取当前币种的信息
 * @param int $id 币种id
 * @return 24H成交量 24H_done_num  24H成交额 24H_done_money 24H涨跌 24H_change 7D涨跌  7D_change
 * @return 最新价格 new_price 买一价 buy_one_price 卖一价 sell_one_price 最高价 max_price 最低价 min_price
 */

function getCurrencyMessageById($id){
    $where['curid']=$id;
    $time=time();
    //一天前的时间
    $old_time=strtotime(date('Y-m-d',$time));
    //最新价格
    $order='ctime desc';
    $rs=M('Orders')->where($where)->order($order)->find();
    $data['new_price']=$rs['price'];
    //总市值
    $currency_info=M('Currency')->find($id);
    $data['zongshizhi']=sprintf("%.2f", ($data['new_price']*$currency_info['currency_all_num']));
    //判断价格是升是降
    $re=M('Orders')->where($where)->where("ctime<$old_time")->order($order)->find();
    if($re['price']>$rs['price']){
        //说明价格下降
        $data['new_price_status']=0;
    }else{
        $data['new_price_status']=1;
    }
    //24H涨跌
    $re=M('Orders')->where($where)->where("ctime<$time-60*60*24")->order($order)->find();
    if ($re['price']!=0){
        $data['24H_change']=sprintf("%.2f", ($rs['price']-$re['price'])/$re['price']*100);
        if($data['24H_change']==0){
            $data['24H_change']=100;
        }
    }else {
        $data['24H_change']=100;
    }
    //7D涨跌
    $re=M('Orders')->where($where)->where("ctime<$time-60*60*24*7")->order($order)->find();
    if ($re['price']!=0){
        $data['7D_change']=sprintf("%.2f", ($rs['price']-$re['price'])/$re['price']*100);
        if($data['7D_change']==0){
            $data['7D_change']=100;
        }
    }else {
        $data['7D_change']=100;
    }
    //24H成交量
    $rs=M('Orders')->field('num')->where($where)->where("ctime>$time-60*60*24")->sum('num');
    $data['24H_done_num']=$rs;
    //24H成交额
//     $rs=M('Orders')->field('num*price')->where($where)->where("ctime>$time-60*60*24")->sum('num*price');
    $rs=M('Orders')->where($where)->where("ctime>$time-60*60*24")->sum('totalMoney');
    $data['24H_done_money']=$rs;
    //最低价
    $data['min_price']=getminPriceTrade($id);
    //最高价
    $data['max_price']=getmaxPriceTrade($id);
    //买一价
    $data['buy_one_price']=getOneOrdersByPrice($id, '2');
    //卖一价
    $data['sell_one_price']=getOneOrdersByPrice($id, '1');
    //返回
    return $data;
}
//获取对应币种，该会员的资产
function getCurrencyUser($uid,$cid){
    $where['member_id']=$uid;
    $where['currency_id']=$cid;
    $rs=M('Currency_user')->field('*,(num+forzen_num) as count')->where($where)->find();
    return $rs;
}
//获取全部币种信息
function currency(){
    $list=M('Currency')->where('is_line=1 ')->order('sort')->select();
    return $list;
}
//获取单独币种信息
function currency_one($id,$field){
    $list=M('Currency')->where("id=".$id)->find();
    if($field){
        $list[$field];
    }
    return $list;
}

//空操作
function _empty(){
    header("HTTP/1.0 404 Not Found");
    $this->display('Public:404');
}

/**
 * 实例化币种
 * @param unknown $currency_id   币种id
 * @return unknown
 */
function getCurrencynameById($currency_id){
    if ($currency_id==0){
        return array('currency_name'=>'人民币','currency_mark'=>'CNY','currency_buy_fee'=>0,'currency_sell_fee'=>0);
    }
    $where['id']= $currency_id;

    $list = M('Currency')->field('currency_name,currency_mark,currency_buy_fee,currency_sell_fee')->where($where)->find();
    return $list;
}
/**
 *
 * @param int $currency_id 币种id
 * @return array 币种结果集
 */
function  getCurrencyByCurrencyId($currency_id=0){
    if (empty($currency_id)) {
        $where['id']=array('gt',$currency_id);
    }else{
        $where['id']=array('eq',$currency_id);
    }
    //获取交易币种信息
    $list= M('Currency')->field("id,price_up,price_down,currency_buy_fee,currency_sell_fee,trade_currency_id,is_lock,rpc_url,rpc_pwd,rpc_user,port_number,currency_all_tibi")->where($where)->select();
    if (!empty($currency_id)) {
        return $list[0];
    }else{
        return $list;
    }
}

/**
 * 获取指定数量个人挂单记录
 * @param int $num 数量
 */
function getOrdersByUser($num,$currency_id,$uid){
    $where['userid']=$uid;
    $where['status']=array('in',array(0,1));
    $where['curid']=$currency_id;
    return  M('Entrust')->where($where)->order("ctime desc")->limit($num)->select();
     
}
 
/**
 * 设置账户资金
 * @param int $currency_id  币种ID
 * @param int $num 交易数量
 * @param char $inc_dec  setDec setInc 是加钱还是减去
 * @param char forzen_num num
 */
function setUserMoney($member_id,$currency_id,$num,$inc_dec,$field,$relevant_uid=NUll){
    $inc_dec=strtolower($inc_dec) ;
    $field=strtolower($field) ;
    //允许传入的字段
    if (!in_array($field, array('num','forzen_num'))){
        return false;
    }
    //如果是RMB
    if ($currency_id==0){
        //修正字段
        switch ($field){
            case 'forzen_num': $field='forzen_money';break;
            case 'num': $field='money';break;
        }
        switch ($inc_dec){
            case 'inc':
                if($field=="forzen_money")
                {
                    $msg= M('User')->where("id=$member_id ")->setInc($field,$num);
                }else
                {
                    $changedate['type']=32;//流水类型
                    $changedate['money']=$num;//操作金额
                    $changedate['remark']="增加";//详细信息
                    $changedate['field']=$field;//字段
                }
                
                break;
            case 'dec':
                if($field=="forzen_money")
                {
                    $msg= M('User')->where("id=$member_id")->setDec($field,$num);
                }else
                {
                    $changedate['type']=29;//流水类型
                    $changedate['money']=0-$num;//操作金额
                    $changedate['remark']="扣除";//详细信息
                    $changedate['field']=$field;//字段
                }
                //
                break;
            default:return false;
        }
        
        if($field=="forzen_money")
        {
            return $msg;
        }else{
            $moneychange_model=D('DetailedBonus');
            
            $changedate['userid']=$member_id;//对应用户
            $changedate['relevant_userid']=$relevant_uid;//起因用户
            
            $res=$moneychange_model->changemoney($changedate);//财务流水记录
        }
        
        return $res;
    }else{
        switch ($inc_dec){
            case 'inc':
                $cur_user=M('Currency_user')->where("member_id=$member_id and currency_id=$currency_id")->find();
                if(empty($cur_user))
                {
                    $cur_userarr=array(
                        'member_id'=>$member_id,
                        'currency_id'=>$currency_id,
                        'num'=>$num,
                        'status'=>1
                    );
                    
                    $msg= M('Currency_user')->add($cur_userarr);
                }else{
                    $msg= M('Currency_user')->where("member_id=$member_id and currency_id=$currency_id")->setInc($field,$num);
                }
                break;
            case 'dec':
                $msg= M('Currency_user')->where("member_id=$member_id and currency_id=$currency_id")->setDec($field,$num);
                break;
            default:return false;
        }
        return $msg;
    }
}
/**
 * 返回指定状态的挂单记录
 * @param int $status -1 0 1 2
 * @param int $num 数量
 * @param int $currency_id 币种id
 */
function getOrdersByStatus($status,$num,$currency_id){
    $where['curid']=$currency_id;
    $where['status']=$status;
    return M('Entrust')->where($where)->limit($num)->order('ctime desc')->select();
}
/**
 * 获取指定数量的成交记录
 * @param int $num
 */
function getTradesByNum($num,$currency_id){
    $where['curid']=$currency_id;
    return M('Orders')->where($where)->order('ctime desc')->limit($num)->select();
}

/**
 * 返回最高价
 @param int $currency_id 币种ID
 */
function getMaxPriceTrade($currency_id){
    $order='desc';
    $trade=getTradeByPrice($currency_id,$order);
    return $trade['price'];
}
/**
 * 返回最低价
 @param int $currency_id 币种ID
 */
 function getminPriceTrade($currency_id){
    $order='asc';
    $trade= getTradeByPrice($currency_id,$order);
    return $trade['price'];
}
/**
 * 指定价格一个成交记录
 * @param int $currency_id 币种ID
 * @param char $order 排序
 */
function getTradeByPrice($currency_id,$order){
    $where['curid']=$currency_id;
    return M('Orders')->field('price')->where($where)->order('price '.$order)->find();

}
/**
 * 返回指定数量排序的挂单记录
 * @param char $type buy sell
 * @param int $num 数量
 * @param char $order 排序 desc asc
 */
function getOrdersByType($currencyid,$type,$num,$order){
    $where['type']=array('eq',$type);
    $where['status']=array('in',array(0,1));
    $where['curid']=$currencyid;
    $list= M('Entrust')->field("sum(wtnum) as num,sum(cjnum) as trade_num,price,type,status")->where($where)->group('price')->order("price $order, ctime asc")->limit($num)->select();
    foreach ($list as $k=>$v){
        $list[$k]['bili']=100-($v['trade_num']/$v['num']*100);
    }
    if ($type=='sell'){
        $list=  array_reverse($list);
    }
    return $list;
}

/**
 * 返回指定数量排序的挂单记录
 * @param int $num 数量
 * @param char $order 排序 desc asc
 */
function getEntrustById($currencyid,$num){
    $where['status']=array('in',array(0,1));
    $where['curid']=$currencyid;
    $list= M('Entrust')->field("sum(wtnum) as num,sum(cjnum) as trade_num,price,type,status")->where($where)->group('price')->order("price desc")->limit($num)->select();//group('price')
    foreach ($list as $k=>$v){
        $list[$k]['weituonum']=($v['num']-$v['trade_num']);
        $list[$k]['type']=($v['type']=="buy")?"买入":"卖出";
    }
    return $list;
}

/**
 * 获取一个挂单记录价格 买一 卖一
 * @param unknown $currencyid
 * @param unknown $type
 * @param unknown $order
 */
function getOneOrdersByPrice($currencyid,$type){
    $where['curid']=$currencyid;
    $where['type']=$type;
    $where['status']=array('in',array(0,1));
    switch ($type){
        case 'buy': $order='desc';
        break;
        case 'sell':$order='asc';
        break;
    }
    $orders= M('Entrust')->field('price')->where($where)->order('price '.$order)->find();
    return $orders['price'];
}


//1:银行卡转账,2:微信支付,3:支付宝支付
function get_pay_text($k){
    $text=array('1'=>'银行卡转账','2'=>'微信支付','3'=>'支付宝支付');
    return $text[$k];
}

//状态,1:未审核,2:通过,-1:未通过
function get_status_text($k){
    $text=array('1'=>'未审核','2'=>'通过','-1'=>'未通过');
    return $text[$k];
}
function get_bankname($k){
    $info=M('Banks')->where(array('id'=>$k))->find();
    return $info['bankName'];
}
function get_uname($k){
    $info=M('User')->where(array('id'=>$k))->find();
    return $info['username'];
}
